package com.zhen.aikan.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.druid.sql.visitor.functions.Now;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.zhen.aikan.entity.History;
import com.zhen.aikan.entity.VodDetail;
import com.zhen.aikan.mapper.HistoryMapper;
import com.zhen.aikan.service.IHistoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhen.aikan.service.IVodDetailService;
import com.zhen.aikan.vo.HistoryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lijiazhen
 * @since 2023-09-11
 */
@Service
public class HistoryServiceImpl extends ServiceImpl<HistoryMapper, History> implements IHistoryService {
    @Autowired
    private IVodDetailService vodDetailService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean addHistory(History history) {
        if (BeanUtil.isEmpty(history)) {
            return false;
        }
        //更新时间
        history.setHistoryTime(LocalDateTime.now());
        //查询是否有记录，有就更新，没有就新增
        boolean exists = baseMapper.exists(new QueryWrapper<History>().eq("user_id", history.getUserId()).eq("vod_id", history.getVodId()));
        if (exists) {
            int update = baseMapper.update(history, new UpdateWrapper<History>().eq("user_id", history.getUserId()).eq("vod_id", history.getVodId()));
            return update > 0;
        }
        //新增前查询该用户的历史记录条数，超过100条就要根据更新时间删除最后一条记录并新增一条
        List<History> histories = baseMapper.selectList(new QueryWrapper<History>().eq("user_id", history.getUserId()).orderByAsc("history_time"));
        if (histories.size() >= 100) {
            History history1 = histories.get(0);
            baseMapper.deleteById(history1.getId());
        }
        return save(history);
    }

    @Override
    public List<HistoryVo> getHistoryByUserId(String userId) {
        if (!StringUtils.hasText(userId)) {
            return null;
        }
        List<History> histories = baseMapper.selectList(new QueryWrapper<History>().eq("user_id", userId).orderByDesc("history_time"));
        List<HistoryVo> historyVos = histories.stream().map(item -> {
            VodDetail vodDetail = vodDetailService.getVodDetailById(item.getVodId());
            HistoryVo historyVo = new HistoryVo();
            BeanUtil.copyProperties(item, historyVo);
            historyVo.setVodName(vodDetail.getVodName());
            historyVo.setVodPicUrl(vodDetail.getVodPic());
            return historyVo;
        }).collect(Collectors.toList());

        return historyVos;
    }
}